<template>
  <div class="app-main-container">
    <div class="doumee-filter">
      <el-form inline @submit.native.prevent>
        <el-form-item label="设备状态:">
          <el-select
            v-model="filters.status"
            placeholder="选择设备状态"
            clearable
          >
            <el-option
              v-for="item in openStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            type="primary"
            @click="getList(1)"
          >查找</el-button>
          <el-button v-preventReClick @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="active" @tab-click="handleClick">
      <el-tab-pane
        v-for="(model, index) in manufacturerList"
        :key="index"
        :label="model.manufacturer"
        :name="index.toString()"
      >
        <div class="doumee-filter manufacturer">
          <div>
            <el-button
              v-if="meta.indexOf('GateAdd') > -1"
              type="primary"
              @click="addDevice"
            >新增</el-button>
            <el-button
              v-if="
                manufacturerList &&
                  manufacturerList.length > 0 &&
                  manufacturerList[active].id != 11
              "
              type="primary"
              @click="tbBtn(manufacturerList[active].id)"
            >同步人员至设备</el-button>
            <el-button
              v-if="
                manufacturerList &&
                  manufacturerList.length > 0 &&
                  manufacturerList[active].id == 16
                  && meta.indexOf('AccountConfig') > -1
              "
              type="primary"
              @click="addDeviceb"
            >账号配置</el-button>
            <!-- <el-button v-if="manufacturerList[active].id == 3" type="primary" @click="bfBtn">一键布防</el-button> -->
          </div>
          <div class="detail" @click="manufacturerDetail(model.id)">
            <i class="el-icon-warning-outline" /> 厂商说明
          </div>
        </div>
      </el-tab-pane>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="
            manufacturerList &&
              manufacturerList.length > 0 &&
              manufacturerList[active].id != 11
          "
          key="id"
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          key="code"
          align="center"
          label="闸机ID"
          prop="code"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          key="name"
          align="center"
          label="闸机名称"
          prop="name"
          min-width="120"
          show-overflow-tooltip
        />
        <!-- <el-table-column align="center" label="加密秘钥" prop="code" width="200" /> -->
        <!-- <el-table-column align="center" key="status" label="状态" min-width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'1'"
              :inactive-value="'0'"
              @change="toConfigUpdate($event, scope.row.id, scope.row.status)"
            />
          </template>
        </el-table-column> -->
        <el-table-column
          key="areaName"
          align="center"
          label="关联场区"
          prop="areaName"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
              manufacturerList.length > 0 &&
              manufacturerList[active].id == 3
          "
          key="ipAddre"
          align="center"
          label="设备ip"
          prop="ipAddre"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
              manufacturerList.length > 0 &&
              manufacturerList[active].id == 3
          "
          key="userAccount"
          align="center"
          label="设备登录用户名"
          prop="userAccount"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
              manufacturerList.length > 0 &&
              manufacturerList[active].id == 3
          "
          key="portCode"
          align="center"
          label="设备端口号"
          prop="portCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          key="status"
          align="center"
          label="状态"
          min-width="80"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              v-preventReClick
              :active-value="'1'"
              :inactive-value="'0'"
              @change="toConfigUpdate($event, scope.row.id, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column
          key="operate"
          label="操作"
          align="center"
          min-width="300"
          fixed="right"
        >
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button
                v-if="
                  manufacturerList[active].functors[0] === '1' &&
                    meta.indexOf('GateEdit') > -1
                "
                v-preventReClick
                type="text"
                @click="toEdit(scope.row)"
              >编辑</el-button>
              <el-button
                v-if="
                  manufacturerList[active].functors[1] === '1' &&
                    meta.indexOf('GateOpenClose') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '1')"
              >常开</el-button>
              <el-button
                v-if="
                  manufacturerList[active].functors[2] === '1' &&
                    meta.indexOf('GateOpenClose') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '2')"
              >常关</el-button>
              <el-button
                v-if="
                  manufacturerList[active].functors[3] === '1' &&
                    meta.indexOf('GateEnable') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '4')"
              >恢复</el-button>
              <el-button
                v-if="
                  manufacturerList[active].functors[4] === '1' &&
                    meta.indexOf('GateController') > -1
                "
                v-preventReClick
                type="text"
                @click="controllBtn(scope.row.code, 0)"
              >开门</el-button>
              <el-button
                v-if="
                  manufacturerList[active].functors[5] === '1' &&
                    meta.indexOf('GateController') > -1
                "
                v-preventReClick
                type="text"
                @click="controllBtn(scope.row.code, 1)"
              >关门</el-button>
              <template v-if=" manufacturerList[active].functors[5] === '1'">
                <el-button
                  v-if="
                    manufacturerList[active].manufacturer === '微光一体机' || manufacturerList[active].manufacturer === '微光二维码'
                  "
                  v-preventReClick
                  type="text"
                  @click="handleOpenLight(scope.row)"
                >开门</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-tabs>
    <!-- <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :current-page.sync="current"
        :total="totalCount"
        @current-change="handleCurrentChange"
      />
    </div> -->
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-dialog
      :title="newDevice.zhpz?'账号配置':'闸机管理'"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="600px"
    >
      <el-form
        ref="newDevice"
        class="doumee-form"
        :model="newDevice"
        :rules="rules"
        label-width="100px"
      >
        <template v-if="newDevice.zhpz">
          <el-form-item label="机构ID" prop="value">
            <el-input
              v-model="newDevice.value"
              class="input-style"
              clearable
              maxlength="30"
              placeholder="请输入机构ID"
            />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="闸机名称" prop="name">
            <el-input
              v-model="newDevice.name"
              class="input-style"
              clearable
              maxlength="30"
              placeholder="请输入闸机名称"
            />
          </el-form-item>
          <el-form-item label="设备id" prop="code">
            <el-input
              v-model="newDevice.code"
              maxlength="30"
              clearable
              class="input-style"
              placeholder="请输入设备id"
            />
          </el-form-item>
          <el-form-item label="厂商" prop="manufacturerId">
            <el-select
              v-model="newDevice.manufacturerId"
              placeholder="选择厂商"
              :disabled="newDevice.id ? true : false"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in manufacturerList"
                :key="item.id"
                :label="item.manufacturer"
                :value="item.id"
              />
            </el-select>
          <!-- <el-input
            v-model="newDevice.manufacturerId"
            class="input-style"
            placeholder="请输入厂商id"
          /> -->
          </el-form-item>
          <el-form-item label="关联场区" prop="areaId">
            <el-select
              v-model="newDevice.areaId"
              placeholder="选择关联场区"
              style="width: 100%"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
                manufacturerList.length > 0 &&
                (manufacturerList[active].id == '12' ||
                  newDevice.manufacturerId == 3)
            "
            label="设备ip"
            prop="ipAddre"
          >
            <el-input
              v-model="newDevice.ipAddre"
              maxlength="30"
              clearable
              class="input-style"
              placeholder="请输入设备ip"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
                manufacturerList.length > 0 &&
                (manufacturerList[active].id == '12' ||
                  newDevice.manufacturerId == 3)
            "
            label="用户名"
            prop="userAccount"
          >
            <el-input
              v-model="newDevice.userAccount"
              maxlength="30"
              class="input-style"
              clearable
              placeholder="请输入设备登录用户名"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
                manufacturerList.length > 0 &&
                (manufacturerList[active].id == '12' ||
                  newDevice.manufacturerId == 3)
            "
            label="设备密码"
            prop="userPassword"
          >
            <el-input
              v-model="newDevice.userPassword"
              class="input-style"
              maxlength="30"
              clearable
              type="password"
              placeholder="请输入设备密码"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
                manufacturerList.length > 0 &&
                (manufacturerList[active].id == '12' ||
                  newDevice.manufacturerId == 3)
            "
            label="端口号"
            prop="portCode"
          >
            <el-input
              v-model="newDevice.portCode"
              class="input-style"
              clearable
              maxlength="30"
              placeholder="请输入设备端口号"
            />
          </el-form-item>
          <!-- <el-form-item label="闸机状态">
          <el-select v-model="newDevice.status" placeholder="暂无">
            <el-option
              v-for="item in deviceStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
          <el-form-item
            v-if="
              newDevice.manufacturerId == 16
            "
            label="出入场方向"
            prop="accessType"
          >
            <el-radio-group v-model="newDevice.accessType">
              <el-radio label="1">入口设备</el-radio>
              <el-radio label="2">出口设备</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="save"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deviceList, accessTypeDetail, accessTypeUpdate, getAreaList, deviceAdd, deviceEdit, deviceStatusChange, deviceController, manufacturerList, manufacturerDetail, syncAllUserToDev, equipmentControl, weiguangOpenLight, bfClick } from '@/api'
import { parseTime } from '@/utils'
import store from '@/store'
export default {
  name: 'Gate',
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      active: '0',
      swiperOptions: {
        slidesPerView: 'auto',
        pagination: {
          el: '.swiper-pagination'
        }
      },
      dialogTableVisible: false,
      totalCount: 0,
      list: [],
      listLoading: true,
      openStatus: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' }
      ],
      deviceStatus: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' }
      ],
      areaList: [],
      manufacturerList: [],
      filters: {},
      newDevice: { projectIds: [] },
      multipleSelection: [],
      pagination: {
        page: 1,
        rows: 10
      },
      rules: {
        value: [
          { required: true, message: '请输入机构ID', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入闸机名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入设备ID', trigger: 'blur' }
        ],
        ipAddre: [
          { required: true, message: '请输入设备ip', trigger: 'blur' }
        ],
        userAccount: [
          { required: true, message: '请输入设备登录用户名', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入设备密码', trigger: 'blur' }
        ],
        accessType: [
          { required: true, message: '请选择出入场方向', trigger: 'change' }
        ],
        areaId: [
          { required: true, message: '请选择关联场地', trigger: 'change' }
        ],
        portCode: [
          { required: true, message: '请输入设备端口号', trigger: 'blur' }
        ],
        manufacturerId: [
          { required: true, message: '请选择厂商', trigger: 'change' }
        ],
        projectIds: [
          { required: true, message: '请选择关联项目', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.listLoading = false
    this.initData()
  },
  activated() {
    if (this.manufacturerList && this.manufacturerList.length > 0) {
      this.$refs.table.doLayout()
    }
  },
  methods: {
    handleClick(tab, event) {
      console.log(this.active)
      this.getList(1)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    toConfigUpdate(e, id, status) {
      deviceStatusChange({ param: { id, status }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.getAreaList()
        }
      }).catch(err => {
        console.log(err)
        this.getAreaList()
      })
    },
    tbBtn(manufacturerId) {
      const that = this
      this.$confirm('此操作将同步人员至设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          syncAllUserToDev({ param: { manufacturerId, venueId: sessionStorage.getItem('venueId') }}).then(res => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('同步成功')
            }
          }).catch(err => {
            ctx.confirmButtonLoading = false
            close()
            console.log(err)
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    bfBtn() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        return this.$message('请选择闸机')
      }
      const ids = this.multipleSelection.map((e) => e.id)
      bfClick({ param: { ids: ids.join(), venueId: sessionStorage.getItem('venueId'), manufacturerId: this.manufacturerList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.$message.success('一键布防成功')
          // this.getList(1)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleOpenLight(row) {
      const that = this
      this.$confirm('此操作将开灯, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          weiguangOpenLight({
            param: {
              deviceSn: row.code,
              manufacturerId: row.manufacturerId
            }
          }).then(res => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('开灯成功')
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    controllBtn(id, type) {
      const that = this
      let str = '开门'
      if (type === 1) {
        str = '关门'
      }
      this.$confirm('此操作将' + str + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          equipmentControl({
            param: {
              id, type, manufacturerId: that.manufacturerList[that.active].id,
              shopId: localStorage.getItem('shopId')
            }
          }).then(res => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              if (type === 0) {
                that.$message.success('开门成功')
              } else {
                that.$message.success('关门成功')
              }
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    addDevice() {
      this.newDevice = {}
      this.dialogTableVisible = true
    },
    addDeviceb() {
      accessTypeDetail({ param: { type: 19 }}).then(res => {
        if (res.errorCode === '000000') {
          if (res.recordList.length > 0) {
            this.newDevice = {
              ...res.recordList[0],
              zhpz: '1'
            }
          } else {
            this.newDevice = {
              zhpz: '1'
            }
          }
          this.dialogTableVisible = true
        }
      })
    },
    toEdit(item) {
      this.dialogTableVisible = true
      this.newDevice = { ...item }
      this.newDevice.manufacturerId = parseInt(item.manufacturerId)
    },
    controllerSet(deskId, flag) {
      deviceController({ param: { deskId, flag }}).then(res => {
        if (res.errorCode === '000000') {
          this.$message.success('切换成功')
        } else {
          this.$message.error('切换失败')
        }
      })
    },
    initData() {
      this.getArea()
      manufacturerList({ param: { type: 0 }}).then(res => {
        if (res.errorCode === '000000') {
          this.manufacturerList = res.recordList
          this.getList(1)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      deviceList({ pagination, gymId: sessionStorage.getItem('venueId'), param: { venueId, manufacturerId: this.manufacturerList[this.active].id, ...filters }}, sessionStorage.getItem('venueId')).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.totalCount = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    getArea() {
      getAreaList({ param: { venueId: sessionStorage.getItem('venueId') }}).then(res => {
        if (res.errorCode === '000000') {
          this.areaList = res.recordList
        }
      })
    },
    clear() {
      this.filters = {}
      this.getList(1)
    },
    cancel() {
      this.dialogTableVisible = false
    },
    save() {
      console.log(this.newDevice)
      this.$refs.newDevice.validate((valid) => {
        if (valid) {
          const param = { ...this.newDevice }
          param.venueId = sessionStorage.getItem('venueId')
          this.subLoading = true
          if (param.zhpz) {
            accessTypeUpdate({ param }, sessionStorage.getItem('venueId')).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('配置成功')
                this.getList(1)
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          } else if (this.newDevice.id) {
            param.id = this.newDevice.id
            deviceEdit({ param }, sessionStorage.getItem('venueId')).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('编辑成功')
                this.getList(1)
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          } else {
            deviceAdd({ param }, sessionStorage.getItem('venueId')).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('新增成功')
                this.getList(1)
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          }
        } else {
          // this.$alert('请先完善设备信息', '错误')
        }
      })
    },
    manufacturerDetail(id) {
      manufacturerDetail({ param: { manufacturerId: this.manufacturerList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        console.log(res)
        if (res.errorCode === '000000') {
          const cont = res.record.manufacturer + res.record.text.replace(/\n/g, '<br/>')
          this.$alert(cont, '厂商说明', {
            dangerouslyUseHTMLString: true
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
